<?php

namespace App\Http\Controllers\Home;

use App\Models\Home\UserInfo;
use App\Models\Home\Weibo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;

class HotController extends Controller
{
    //显示热点
    public function index()
    {
        //所有微博
        //$hot = Weibo::all()->toArray();
        $hot = Weibo::leftJoin('user_infos', 'user_infos.user_id', '=', 'weibos.user_id')
            ->select('weibos.*', 'user_infos.user_id', 'user_infos.nickname', 'user_infos.avatar')
            ->where('weibos.is_show', 1)
            ->where('weibos.is_forward', null)
            ->get()
            ->toArray();

        //当前用户id
        $user_id = Session::get('user.id');
        if ($user_id) {
            //获取收藏点赞信息
            $a = UserInfo::select('favorites', 'likes')
                ->where('user_id', '=', $user_id)
                ->first()
                ->toArray();

            //全部微博中增加收藏点赞标识
            foreach ($hot as $k => $v) {
                $hot[$k]['favorites'] = $a['favorites'];
                $hot[$k]['likes'] = $a['likes'];
            }
        }

        //遍历所有微博 按权重计算分数
        foreach ($hot as $k => $v) {
            $hot[$k]['score'] = $v['forward_num'] * 0.3 + $v['comment_num'] * 0.6 + $v['like_num'] * 0.1;
        }

        //二维数组按指定字段排序
        function my_array_multisort($data, $sort_order_field, $sort_order = SORT_DESC, $sort_type = SORT_NUMERIC)
        {
            foreach ($data as $val) {
                $key_arrays[] = $val[$sort_order_field];
            }
            array_multisort($key_arrays, $sort_order, $sort_type, $data);
            return $data;
        }
        if (!empty($hot)) {
            $data = my_array_multisort($hot, 'score');
        } else {
            $data = [];
        }

        return view('home.hot', ['feeds' => $data]);
    }
}
